package Dao;

import Table.Book;
import Utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class SearchGiveByPageDao {
    public static int SearchTotalCount(String bookname, String auther, int user_id) {
        String bookname1 = "%" + bookname + "%";
        String auther1 = "%" + auther + "%";
        int totalCount = 0;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DruidUtils.getConnection();
            String sql = "select count(*) from book,borrowbook " +
                    "where book.bookname like ? and book.auther like ? " +
                    "and borrowbook.user_id=? and borrowbook.book_id=book.id " +
                    "order by book.id";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, bookname1);
            pstmt.setString(2, auther1);
            pstmt.setInt(3, user_id);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                totalCount = rs.getInt(1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtils.close(rs, pstmt, conn);
        }

        return totalCount;
    }

    public static ArrayList<Book> SearchByPage(int start, int rows, String bookname, String auther, int user_id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String bookname1 = "%" + bookname + "%";
        String auther1 = "%" + auther + "%";
        ArrayList<Book> list = new ArrayList<>();
        try {
            conn = DruidUtils.getConnection();
            String sql = "select * from book,borrowbook " +
                    "where book.bookname like ? and book.auther like ? " +
                    "and borrowbook.user_id=? and borrowbook.book_id=book.id " +
                    "order by book.id limit ?,?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, bookname1);
            pstmt.setString(2, auther1);
            pstmt.setInt(3, user_id);
            pstmt.setInt(4, start);
            pstmt.setInt(5, rows);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setBookname(rs.getString("bookname"));
                book.setAuther(rs.getString("auther"));
                book.setPrice(rs.getInt("price"));
                book.setNums(rs.getInt("nums"));
                list.add(book);
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DruidUtils.close(rs, pstmt, conn);
        }
        return list;
    }
}
